package com.bj58.ecdata.mailreport.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import org.apache.commons.lang.reflect.FieldUtils;
import org.springframework.util.StringUtils;

import com.bj58.groupbuy.action.util.PatternUtil;





/**
 * @author huangliang
 *升序  将List<String>  String(key_count)  根据key(int)大小排序
 */
@SuppressWarnings("rawtypes")
class SortComparator_key_int implements Comparator {


	public int compare(Object o1, Object o2) {
	
	 if (o1 == null || o2 == null)
        
           return 0; 
		
     int v1 = Integer.parseInt(o1.toString().substring(0,o1.toString().indexOf("_")));
	
	 int v2 = Integer.parseInt(o2.toString().substring(0,o2.toString().indexOf("_")));
      
	 return v1>v2?1:-1;
	
    }

}


/**
 * @author huangliang
 *升序  将List<String>  String(key_count)  根据key(date)大小排序
 */
@SuppressWarnings("rawtypes")
class SortComparator_key_date implements Comparator {


	public int compare(Object o1, Object o2) {
	
		 if (o1 == null || o2 == null)
	        
	           return 0; 
			
	     Date v1 = DateUtil.parseSimpleDateTime((o1.toString().substring(0,o1.toString().indexOf("_"))), "yyyy-MM-dd");
		
	     Date v2 = DateUtil.parseSimpleDateTime((o2.toString().substring(0,o2.toString().indexOf("_"))), "yyyy-MM-dd");
	     
	     
	      
	     return v1.after(v2)?1:-1;
		
    }

}




/**
 * @author huangliang
 *降序
 */
@SuppressWarnings("rawtypes")
class DescendComparator implements Comparator { 

	public int compare(Object o1, Object o2) {
	
	 if (o1 == null || o2 == null)
        
           return 0; 
		
     double v1 = Double.valueOf(o1.toString().substring(o1.toString().indexOf("_")+1));
	
     double v2 = Double.valueOf(o2.toString().substring(o2.toString().indexOf("_")+1));
      
         return v1<v2?1:-1;
	
    }

}


@SuppressWarnings("rawtypes")
class SortComparatorByKeyLengthDesc implements Comparator {
	public int compare(Object o1, Object o2) {
		 if (o1 == null || o2 == null){
			 return 0; 
		 }
	     
		 int length1 = o1.toString().length();
		 int length2 = o2.toString().length();
		 
		 return length1<length2?1:-1;
    }
}


public class SortUtil {
	/**对key_count集合进行降序排序(按照count数值大小)  并取前max个
	 * @param values
	 * @param max  排序后取前多少个
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<String> DescendByCount(List<String> values,int max){
		//排序
		DescendComparator cc=new DescendComparator();
		TreeSet<String> ts=new TreeSet<String>(cc);
		ts.addAll(values);
		//截取前max个
		List<String> sortValues = new ArrayList<String>();
		int count = 0;
		Iterator<String> it = ts.iterator();
		while(it.hasNext()){
			sortValues.add(it.next());
			count++;
			if(count == max){
				break;
			}
		}
		
		return sortValues;
	}
	
	
	/**对key_count集合进行升序排列  （按照KEY(int)）大小
	 * @param values
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<String> AscByKey_int(List<String> values){
		SortComparator_key_int cc=new SortComparator_key_int();
		TreeSet<String> ts=new TreeSet<String>(cc);
		ts.addAll(values);
		return new ArrayList<String>(ts);
	}
	
	
	/**对key_count集合进行升序排列  （按照KEY(date)）大小
	 * @param values
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<String> AscByKey_date(List<String> values){
		SortComparator_key_date cc=new SortComparator_key_date();
		TreeSet<String> ts=new TreeSet<String>(cc);
		ts.addAll(values);
		return new ArrayList<String>(ts);
	}
	
	

	/**按照list中的字符长度 降序 排列
	 * @param values
	 */
	@SuppressWarnings("unchecked")
	public static List<String> sortListByLengthDesc (List<String> values){
		SortComparatorByKeyLengthDesc cc  = new SortComparatorByKeyLengthDesc();
		TreeSet<String> ts=new TreeSet<String>(cc);
		ts.addAll(values);
		return new ArrayList<String>(ts);
	}
	
	

	
	
	/** 自定义报表  跨表查询 重新排序
	 * @param dataList  排序数据
	 * @param orderBy  排序逻辑
	 * @param cols   数据结果对应字段集（用于确认排序的数据下标）
	 * @return
	 */
	public static List<String>  sortIRData(List<String> dataList , String orderBy,List<String> cols)throws Exception{
		if("".equals(orderBy)){
			return dataList;
		}
		//暂时默认只对第一个分组维度进行重新排序  多重组合排序效率太慢  待优化
		orderBy = orderBy.toLowerCase().replace("order", "").replace("by", "").trim();
		String orderFirstValue = orderBy.split(",")[0];
		int sortType = 1; // 1:升序  2:降序
		if(orderFirstValue.contains("desc")){
			sortType = 2;
		}
		
		orderFirstValue = orderFirstValue.replace("desc", "").replace("asc", "");
		int sortValueIndex = 0 ;
		for(int i = 0 ; i < cols.size() ; i ++){
			String checkCol = cols.get(i);
			if(checkCol.trim().toLowerCase().equals(orderFirstValue.trim().toLowerCase())){
				sortValueIndex = i;
				break;
			}
		}
		return sortList(dataList, sortValueIndex, sortType);
	}
	
    
    /**根据指定字段的值 对List<T>进行排序    指定字段必须为数字(int or double)
     * @param <T>
     * @param fileName 排序字段名
     * @param sortType   1:升序  2:降序
     */
	public <T>List<T>  sortListByFileNameVo(List<T> rsList , Class<T> clazz , String fileName, int sortType)throws Exception{
    	
		//字段数据类型
		Field field = clazz.getDeclaredField(fileName);
		Class<?> filedCls = field.getType();
		
		for(int i = 0 ; i < rsList.size() - 1 ; i ++){
			T tempVo1 = clazz.newInstance();
			T tempVo2 = clazz.newInstance();
			for(int j = 0 ; j <  rsList.size() - 1 - i ; j++){
				Object value1 = FieldUtils.readField(rsList.get(j),fileName,  true);
				Object value2 =  FieldUtils.readField(rsList.get(j+1),fileName,  true);;
				
				
				if(filedCls == int.class || filedCls == Integer.class || filedCls == long.class || filedCls == Long.class) {
					int comp1 = Integer.parseInt(value1.toString());
					int comp2 = Integer.parseInt(value2.toString());
					if(sortType == 1){ //升序
						if(comp1 > comp2){
							tempVo1 = rsList.get(j);
							tempVo2 = rsList.get(j+1);
							
							rsList.remove(j+1);
							rsList.remove(j);
							
							rsList.add(j, tempVo2);
							rsList.add(j+1, tempVo1);
							
						}
					}else if(sortType == 2){ //降序
						if(comp1 < comp2){
							tempVo1 = rsList.get(j);
							tempVo2 = rsList.get(j+1);
							
							rsList.remove(j+1);
							rsList.remove(j);
							
							rsList.add(j, tempVo2);
							rsList.add(j+1, tempVo1);
							
						}
					}
					
				}else if(filedCls == double.class || filedCls == Double.class) {
					double comp1 = Double.parseDouble(value1.toString());
					double comp2 = Double.parseDouble(value2.toString());
					if(sortType == 1){ //升序
						if(comp1 > comp2){
							tempVo1 = rsList.get(j);
							tempVo2 = rsList.get(j+1);
							
							rsList.remove(j+1);
							rsList.remove(j);
							
							rsList.add(j, tempVo2);
							rsList.add(j+1, tempVo1);
							
						}
					}else if(sortType == 2){ //降序
						if(comp1 < comp2){
							tempVo1 = rsList.get(j);
							tempVo2 = rsList.get(j+1);
							
							rsList.remove(j+1);
							rsList.remove(j);
							
							rsList.add(j, tempVo2);
							rsList.add(j+1, tempVo1);
							
						}
					}
				} 
				
			}
			
		}
		
		
    	return rsList;
    }
    
    /**根据指定字符串下标位置对List<String>进行排序    指定字段必须为数字(int or double)
	  * @author zhaoxiang     自定义邮件行排序
   * @param sortValueIndex  排序字段下标位置
   * @param sortType   1:升序  2:降序
   * @throws Exception
   */
	public static List<String>  sortIEList(List<String> rsList ,int sortValueIndex, int sortType)throws Exception{
		for(int i = 0 ; i < rsList.size() - 1 ; i ++){
			String tempVo1 = "";
			String tempVo2 = "";
			for(int j = 0 ; j <  rsList.size() - 1 - i ; j++){
				Object value1 = rsList.get(j).split(";")[sortValueIndex];
				Object value2 = rsList.get(j + 1).split(";")[sortValueIndex];
				
				String v1=StringUtils.deleteAny(value1.toString(), ",% ");
				String v2=StringUtils.deleteAny(value2.toString(), ",% ");
				
				if("--".equals(v1))
					v1="0";	
				if("--".equals(v2))
					v2="0";
				double comp1 = Double.parseDouble(v1);
				double comp2 = Double.parseDouble(v2);
				//double comp1 = Double.parseDouble(StringUtils.deleteAny(value1.toString(), ",% "));
				//double comp2 = Double.parseDouble(StringUtils.deleteAny(value2.toString(), ",% "));
				if (sortType == 1) { // 升序
					if (comp1 > comp2) {
						tempVo1 = rsList.get(j);
						tempVo2 = rsList.get(j + 1);

						rsList.remove(j + 1);
						rsList.remove(j);

						rsList.add(j, tempVo2);
						rsList.add(j + 1, tempVo1);

					}
				} else if (sortType == 2) { // 降序
					if (comp1 < comp2) {
						tempVo1 = rsList.get(j);
						tempVo2 = rsList.get(j + 1);

						rsList.remove(j + 1);
						rsList.remove(j);

						rsList.add(j, tempVo2);
						rsList.add(j + 1, tempVo1);

					}
				}
				
			}
		}
  	return rsList;
  }

    
    /**根据指定字符串下标位置对List<String>进行排序    指定字段字符串
	  * @author zhaoxiang     自定义邮件行排序
   * @param sortValueIndex  排序字段下标位置
   * @param sortType   1:升序  2:降序
   * @throws Exception
   */
	public static List<String>  sortIEListForStr(List<String> rsList ,int sortValueIndex, int sortType)throws Exception{
		for(int i = 0 ; i < rsList.size() - 1 ; i ++){
			String tempVo1 = "";
			String tempVo2 = "";
			for(int j = 0 ; j <  rsList.size() - 1 - i ; j++){
				Object value1 = rsList.get(j).split(";")[sortValueIndex];
				Object value2 = rsList.get(j + 1).split(";")[sortValueIndex];
				
				String comp1 = StringUtils.deleteAny(value1.toString(), ",% ");
				String comp2 = StringUtils.deleteAny(value2.toString(), ",% ");
				if (sortType == 1) { // 升序
					if (comp1.compareTo(comp2)>=0) {
						tempVo1 = rsList.get(j);
						tempVo2 = rsList.get(j + 1);

						rsList.remove(j + 1);
						rsList.remove(j);

						rsList.add(j, tempVo2);
						rsList.add(j + 1, tempVo1);
					}
				} else{ // 降序
					if (comp1.compareTo(comp2) < 0) {
						tempVo1 = rsList.get(j);
						tempVo2 = rsList.get(j + 1);

						rsList.remove(j + 1);
						rsList.remove(j);

						rsList.add(j, tempVo2);
						rsList.add(j + 1, tempVo1);

					}
				}
				
			}
		}
  	return rsList;
  }
	
	
	 /**根据指定字符串下标位置对List<String>进行排序    指定字段必须为数字(int or double)
     * @param sortValueIndex  排序字段下标位置
     * @param sortType   1:升序  2:降序
     * @throws Exception
     */
	public static List<String>  sortList(List<String> rsList ,int sortValueIndex, int sortType)throws Exception{
		for(int i = 0 ; i < rsList.size() - 1 ; i ++){
			String tempVo1 = "";
			String tempVo2 = "";
			for(int j = 0 ; j <  rsList.size() - 1 - i ; j++){
				Object value1 = rsList.get(j).split(";")[sortValueIndex];
				Object value2 = rsList.get(j + 1).split(";")[sortValueIndex];
				
				if(baseSort(value1, value2, sortType)){
					tempVo1 = rsList.get(j);
					tempVo2 = rsList.get(j + 1);

					rsList.remove(j + 1);
					rsList.remove(j);

					rsList.add(j, tempVo2);
					rsList.add(j + 1, tempVo1);
				}
				
			}
		}
    	return rsList;
    }
	
	
	private  static boolean baseSort(Object value1,Object value2 , int sortType)throws Exception{
		if(value1.toString().contains(",")){
			value1 = value1.toString().split(",")[0];
		}
		
		if(value2.toString().contains(",")){
			value2 = value2.toString().split(",")[0];
		}
		
		if(PatternUtil.onlyHasNum(value1.toString()) && PatternUtil.onlyHasNum(value2.toString()) ){ //数字排序
			double comp1 = Double.parseDouble(value1.toString().replace(",", ""));
			double comp2 = Double.parseDouble(value2.toString().replace(",", ""));
			if (sortType == 1 && comp1 > comp2 ) { // 升序
				return true;
			}else if (sortType == 2 && comp1 < comp2 ) { // 降序
				return true;
			}	
		}else if(PatternUtil.isDate(value1.toString()) && PatternUtil.isDate(value2.toString()) ){ //日期 ( yyyy-MM-dd)
			Date comp1 = DateUtil.strToDate(value1.toString(), "yyyy-MM-dd");
			Date comp2 = DateUtil.strToDate(value2.toString(), "yyyy-MM-dd");
			if (sortType == 1 && comp1.after(comp2) ) { // 升序
				return true;
			}else if (sortType == 2 && comp1.before(comp2) ) { // 降序
				return true;
			}	
		}else{ // 中英文取首字节转ASC
			int comp1 = (int)value1.toString().toCharArray()[0];
			int comp2 = (int)value2.toString().toCharArray()[0];
			if (sortType == 1 && comp1 > comp2 ) { // 升序
				return true;
			}else if (sortType == 2 && comp1 < comp2 ) { // 降序
				return true;
			}	
		}
		return false;
	}
	
	
}

